package com.newzqxq.koalamoney.common;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;

import com.newzqxq.koalamoney.R;
import com.newzqxq.koalamoney.utils.AppUtils;
import com.newzqxq.koalamoney.utils.MyToast;
import com.newzqxq.koalamoney.utils.StatusBarUtil;
import com.newzqxq.koalamoney.view.IBaseView;
import com.newzqxq.koalamoney.widget.dialog.AlertDialog;

import java.util.List;

import butterknife.ButterKnife;

/**
 * 基类
 * Created by ZQXQ-Developer on 2017/7/13.
 */

public abstract class BaseActivity extends AppCompatActivity implements IBaseView {
    private static PermissionListener mPermissionListener;
    private int mRequestCode;
    protected Context mContext;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        //        //修改状态栏为全透明
        StatusBarUtil.setStatusBarColor(this, R.color.colorPrimary);
        if (getContentViewId() != 0) {
            setContentView(getContentViewId());
            ButterKnife.bind(this);
        }

        initView();
        initData();
        initListener();
        AppUtils.addActivity(this);
        //写死竖屏
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }

    /**
     * 设置
     *
     * @return
     */
    protected abstract int getContentViewId();

    /**
     * 初始化数据
     */
    protected abstract void initData();

    /**
     * 初始化View
     */
    protected abstract void initView();

    /**
     * 初始化监听
     */
    protected abstract void initListener();

    /**
     * 清理内存
     */
    protected abstract void clearMemory();

    /**
     * 显示Toast
     *
     * @param str
     */
    protected void showShortToast(String str) {
        Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (!isAppOnForeground()) {
//            showShortToast("从前台返回到后台");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        AppUtils.removeActivity(this);
    }

    /**
     * 程序是否在前台运行
     *
     * @return
     */
    public boolean isAppOnForeground() {
        ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
        String packageName = getApplicationContext().getPackageName();
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
                .getRunningAppProcesses();
        if (appProcesses == null)
            return false;
        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(packageName)
                    && appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true;
            }
        }
        return false;
    }


    /**
     * 其他 Activity 继承 BaseActivity 调用 performRequestPermissions 方法
     *
     * @param desc        首次申请权限被拒绝后再次申请给用户的描述提示
     * @param permissions 要申请的权限数组
     * @param requestCode 申请标记值
     * @param listener    实现的接口
     */
    protected void myRequestPermissions(String desc, String[] permissions, int requestCode, PermissionListener listener) {
        if (permissions == null || permissions.length == 0) {
            return;
        }
        mRequestCode = requestCode;
        mPermissionListener = listener;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkEachSelfPermission(permissions)) {// 检查是否声明了权限
                requestEachPermissions(desc, permissions, requestCode);
            } else {// 已经申请权限
                if (mPermissionListener != null) {
                    mPermissionListener.onPermissionGranted();
                }
            }
        } else {
            if (mPermissionListener != null) {
                mPermissionListener.onPermissionGranted();
            }
        }
    }

    /**
     * 申请权限前判断是否需要声明
     *
     * @param desc
     * @param permissions
     * @param requestCode
     */
    private void requestEachPermissions(String desc, String[] permissions, int requestCode) {
        if (shouldShowRequestPermissionRationale(permissions)) {// 需要再次声明
            showRationaleDialog(desc, permissions, requestCode);
        } else {
            ActivityCompat.requestPermissions(BaseActivity.this, permissions, requestCode);
        }
    }

    /**
     * 弹出声明的 Dialog
     *
     * @param desc
     * @param permissions
     * @param requestCode
     */
    private void showRationaleDialog(String desc, final String[] permissions, final int requestCode) {
        final AlertDialog dialog = new AlertDialog(this).builder();
        dialog.setTitle("温馨提示");
        dialog.setMsg(desc);
        dialog.setPositiveButton("确定", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ActivityCompat.requestPermissions(BaseActivity.this, permissions, requestCode);
            }
        });
        dialog.setNegativeButton("退出程序", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
                dialog.dismiss();
            }
        });
        dialog.setCancelable(false);
        dialog.show();
    }


    /**
     * 再次申请权限时，是否需要声明
     *
     * @param permissions
     * @return
     */
    private boolean shouldShowRequestPermissionRationale(String[] permissions) {
        for (String permission : permissions) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
                return true;
            }
        }
        return false;
    }


    /**
     * 检察每个权限是否申请
     *
     * @param permissions
     * @return true 需要申请权限,false 已申请权限
     */
    private boolean checkEachSelfPermission(String[] permissions) {
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                return true;
            }
        }
        return false;
    }

    /**
     * 申请权限结果的回调
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == mRequestCode) {
            if (checkEachPermissionsGranted(grantResults)) {
                if (mPermissionListener != null) {
                    mPermissionListener.onPermissionGranted();
                }
            } else {// 用户拒绝申请权限
                if (mPermissionListener != null) {
//                    mPermissionListener.onPermissionDenied();
                    showDialog();
                }
            }
        }
    }


    private void showDialog() {
        final AlertDialog dialog = new AlertDialog(this).builder();
        dialog.setTitle("温馨提示");
        dialog.setMsg("为了更好的服务予您，我们需要这些必要权限并不会侵犯您的隐私！是否手动去开启？");
        dialog.setCancelable(false);
        dialog.setPositiveButton("去开启", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                enterSetting();
            }
        });
        dialog.setNegativeButton("退出程序", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                finish();
            }
        });
        dialog.show();
    }

    /**
     * 检查回调结果
     *
     * @param grantResults
     * @return
     */
    private boolean checkEachPermissionsGranted(int[] grantResults) {
        for (int result : grantResults) {
            if (result != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    /**
     * 跳转至当前应用的设置界面
     */
    private void enterSetting() {
        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
        localIntent.setData(Uri.fromParts("package", getPackageName(), null));
        startActivity(localIntent);
    }

    /**
     * View 层基类接口方法
     *
     * @param toast 显示 toast 提示
     */
    @Override
    public void onShowToast(String toast) {
        MyToast.shortToast(mContext, toast);
    }

    /**
     * View 层基类接口方法
     *
     * @param show 是否显示加载提示
     */
    @Override
    public void onShowLoading(boolean show) {
        onShowLoading(show, true);
    }

    /**
     * @param show       是否显示加载提示
     * @param cancelAble 是否可以取消提示窗
     */
    @Override
    public void onShowLoading(boolean show, boolean cancelAble) {

    }
}
